package com.lgt_enterprise_android.utils;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;

import androidx.core.app.NotificationCompat;

import com.bumptech.glide.request.RequestOptions;
import com.lgt_enterprise_android.Constant;
import com.lgt_enterprise_android.R;

import java.io.File;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CommonUtil {

    public static String getCurrentDate() {
        Calendar calendar=Calendar.getInstance();

        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH)+1;
        String strMonth=month>9 ? month+"" : "0"+month;
        int day=calendar.get(Calendar.DAY_OF_MONTH);
        String strDay=day>9 ? day+"" : "0"+day;

        return year+"-"+strMonth+"-"+strDay;
    }


    public static String getGenderStr(int gender) {
        if (gender == 1) {
            return "男";
        } else if (gender == 2) {
            return "女";
        }
        return "性别未知";
    }

    public static void scrollToPos(int start, int end, final View view) {
        ValueAnimator animator = ValueAnimator.ofInt(start, end);
        animator.setDuration(250);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                view.scrollTo(0, (Integer) valueAnimator.getAnimatedValue());
            }
        });
        animator.start();
    }

    // 时间戳转化为 时分秒
    public static String getTimeFromTimeSJC(String timetemp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(timetemp);
        Date date = new Date(lt * 1000L);
        return simpleDateFormat.format(date);
    }


    //设置推送的小红点
    public static void setBadge(Context context, int num) {
        if ("HONOR".equals(Build.BRAND) || "Huawei".equalsIgnoreCase(Build.BRAND)) {
            try {
                String pName = context.getPackageName();
                Bundle bunlde = new Bundle();
                bunlde.putString("package", pName); // 包名
                bunlde.putString("class", "com.lgt_enterprise_android.view.pages.SplashActivity");
                bunlde.putInt("badgenumber", num);
                Bundle res = context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, bunlde);
            } catch (Exception e) {
                int a = 1;
            }
        } else if ("Xiaomi".equalsIgnoreCase(Build.BRAND)) {
            setBadgeOfMIUI(context, num, R.mipmap.ic_launcher);
        }
    }

    private static void setBadgeOfMIUI(Context context, int count, int iconResId) {
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle("标题").setContentText("消息正文").setSmallIcon(iconResId);
        Notification notification = builder.build();
        try {
            Field field = notification.getClass().getDeclaredField("extraNotification");
            Object extraNotification = field.get(notification);
            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
            method.invoke(extraNotification, count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mNotificationManager.notify(0, notification);
    }


    public static void hideBottomUIMenu(Activity activity) {
        View decorView = activity.getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    /**
     * 判断手机号是否有效
     *
     * @param phoneNum 手机号
     * @return 有效则返回true, 无效则返回false
     */
    public static boolean isPhoneNumValid(String phoneNum) {
        return phoneNum.length() == 11 && phoneNum.startsWith("1");
    }


    /**
     * 在按钮上启动一个定时器，用于获取验证码的操作
     *
     * @param tvVerifyCode  验证码控件
     * @param defaultString 按钮上默认的字符串
     * @param max           失效时间（单位：s）
     * @param interval      更新间隔（单位：s）
     */
    public static void startTimer(final WeakReference<TextView> tvVerifyCode,
                                  final String defaultString,
                                  int max,
                                  int interval) {
        tvVerifyCode.get().setEnabled(false);

        // 由于CountDownTimer并不是准确计时，在onTick方法调用的时候，time会有1-10ms左右的误差，这会导致最后一秒不会调用onTick()
        // 因此，设置间隔的时候，默认减去了10ms，从而减去误差。
        // 经过以上的微调，最后一秒的显示时间会由于10ms延迟的积累，导致显示时间比1s长max*10ms的时间，其他时间的显示正常,总时间正常
        new CountDownTimer(max * 1000, interval * 1000 - 10) {

            @Override
            public void onTick(long time) {
                // 第一次调用会有1-10ms的误差，因此需要+15ms，防止第一个数不显示，第二个数显示2s
                if (null == tvVerifyCode.get()) {
                    this.cancel();

                } else {
                    tvVerifyCode.get().setText("" + ((time + 15) / 1000) + "s");
                    tvVerifyCode.get().setTextColor(Color.parseColor("#737373"));
                }
            }

            @Override
            public void onFinish() {
                if (null == tvVerifyCode.get()) {
                    this.cancel();
                    return;
                }
                tvVerifyCode.get().setEnabled(true);
                tvVerifyCode.get().setText(defaultString);
                tvVerifyCode.get().setTextColor(Color.parseColor("#FFB802"));
            }
        }.start();
    }

//    public static void takePicFromGallery(Activity activity) {
////        File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "image/DZ");
////        Intent intent = new Intent(Intent.ACTION_PICK, Uri.fromFile(appDir));
////        intent.setData(Uri.fromFile(appDir));
////        intent.setType("image/*");
////        activity.startActivityForResult(Intent.createChooser(intent, "Select File"),Constant.GALLERY_APP);
//
//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_PICK);
//        intent.setType("image/*");
//        activity.startActivityForResult(intent, Constant.GALLERY_APP);
//    }


    public static RequestOptions getCircelGlideOptions() {
        return RequestOptions.circleCropTransform().error(R.drawable.icon_head).error(R.drawable.icon_head);//不做内存缓存
    }

    public static RequestOptions getGlideOptions() {
        return  RequestOptions.centerCropTransform().error(R.drawable.icon_head).error(R.drawable.icon_head);//不做内存缓存
    }


    public static void takePicFromGallery(Activity activity) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent, Constant.GALLERY_APP);
    }

    public static String getRealPathFromURI(Activity activity, Uri contentUri) {
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }

    public static void takePicFromCamera(Activity activity, int requestCode, String filePath) {
        File file = activity.getExternalCacheDir();
        if (!file.exists()) {
            file.mkdir();
        }

        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File picPath = new File(file.getPath(), filePath);
        Constant.mCamRequestedUri = Uri.fromFile(picPath);

        if (Build.VERSION.SDK_INT < 24) {
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Constant.mCamRequestedUri);
            activity.startActivityForResult(openCameraIntent, requestCode);
        } else {
            //适配Android7.0
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, picPath.getAbsolutePath());
            Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
//            activity.grantUriPermission( "com.example.lab.android.nuc.chat",uri,Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            openCameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            activity.startActivityForResult(openCameraIntent, requestCode);
        }
    }


}
